package com.ssl.order.pay.factory;

import com.ssl.order.pay.strategy.IPayStrategy;
import com.ssl.order.pay.strategy.PayContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * payContext工厂
 */
@Component
public class PayContextFactory {
    //借鉴享元模式，创建Map结构缓存不同的 PayContext类
    private static final Map<String, PayContext> payContexts = new ConcurrentHashMap<>();


    public PayContext getContext(Integer payType){
        StrategyEnum strategyEnum =
                payType == 1 ? StrategyEnum.alipay :
                        payType == 2 ? StrategyEnum.wechat : null;
        if(strategyEnum == null) {
            throw new UnsupportedOperationException("payType not found!");
        }

        PayContext context = payContexts.get(strategyEnum.name());
        if (context == null) {
            try {
                IPayStrategy payStrategy =
                        (IPayStrategy) Class.forName(strategyEnum.getValue()).newInstance();
                PayContext payContext = new PayContext(payStrategy);
                payContexts.put(strategyEnum.name(), payContext);
            } catch (Exception e) {
                throw new UnsupportedOperationException("Get PayStrategy failed!");
            }
        }
        return context;
    }
}
